﻿using PuppeteerSharp;
using Q.Spider.Core;
using Q.Spider.Common;
using Q.Spider.Core.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace Q.Spider.Sample.Flow
{
    public class TaoPiaoPiao : Q.Spider.Core.FlowBase
    {
        public override async Task RunAsync(FlowContext Context)
        {

            //添加请求时可以根据Name匹配流
            //在抓取任务中
            if (Request.Name != "淘票票")
            {
                return;
            }
            //模拟抓取城市信息
            await City();
        }



        private async Task City()
        {
            //加载页面
            await Engine.StartLoad(Request.Uri.ToString());

            //等待页面异步加载Dom
            try
            {
                await Engine.WaitForSelectorAsync("#cityName", new WaitForSelectorOptions()
                {
                    Timeout = 5000
                });
            }
            catch (Exception)
            {
                LogHelper.Logger.Error("超时：" + Request.Uri);
                Context.State = FlowContextHandelState.错误;
                return;
            }

            //获取当前页对象
            var page = Engine.CurrentPage;

            //获取Dom位置
            var rect = await Engine.GetBoundingClientRect("#cityName");

            await Task.Delay(200);
            //移动光标至节点上
            await page?.Mouse.MoveAsync(rect.X, rect.Y);

            await Task.Delay(5000);

            //获取信息
            var list = await Engine.QuerySelectorAllAsync(".cityList a");
            var info = new Dictionary<string, string>();
            foreach (var item in list)
            {
                var href = await (await item.GetPropertyAsync("href")).JsonValueAsync<string>();
                var text = await (await item.GetPropertyAsync("innerText")).JsonValueAsync<string>();

                var id = Tools.GetUrlQueryString(href, "city");

                if (id == null)
                {
                    LogHelper.Logger.Info($"抓取城市：{text} id等于null");
                }
                else
                {
                    info.TryAdd(id, text);
                    LogHelper.Logger.Info($"抓取城市：{text}  id:{id}");
                }
            }
            Request.AddProperties("info", info);
        }



        public static void AddTestRequest(QSpiderCore core)
        {
            var requestCity = new Core.Models.Request("https://dianying.taobao.com/")
            {
                Name = "淘票票"
            };
            core.AddRequest(requestCity);

        }
    }
}
